package com.hiabr.iep.common.web.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hiabr.iep.common.domain.context.ThreadLocalContext;
import com.hiabr.iep.common.domain.vo.req.BaseAdminReq;
import com.hiabr.iep.common.domain.vo.req.BaseUserReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description DML自动填充字段值
 */
@Slf4j
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = 0L;
        BaseUserReq user = ThreadLocalContext.getUser();
        if (user != null) {
            userId = user.getUserId();
        } else {
            BaseAdminReq admin = ThreadLocalContext.getAdmin();
            if (admin != null) {
                userId = admin.getUserId();
            }
        }
        Date now = new Date();
        this.setFieldValByName("createBy", userId, metaObject);
        this.setFieldValByName("createTime", now, metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
        this.setFieldValByName("updateTime", now, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = 0L;
        BaseUserReq user = ThreadLocalContext.getUser();
        if (user != null) {
            userId = user.getUserId();
        } else {
            BaseAdminReq admin = ThreadLocalContext.getAdmin();
            if (admin != null) {
                userId = admin.getUserId();
            }
        }
        Date now = new Date();
        this.setFieldValByName("updateBy", userId, metaObject);
        this.setFieldValByName("updateTime", now, metaObject);
    }
}
